/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.terminalrodoviario.servlets;

import br.Db;
import br.terminalrodoviario.Route;
import br.terminalrodoviario.RouteItinerary;
import br.terminalrodoviario.RouteTime;
import br.terminalrodoviario.RouteTravel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author marcelo
 */
public class RouteTimeServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String id = request.getParameter("id");
            int type = Integer.parseInt(request.getParameter("type"));
            Route r = new Route();
            r.setId(Integer.parseInt(request.getParameter("route")));           
            
            RouteTravel rtv = new RouteTravel();
            rtv.setRoute(r);
            rtv.setType(type);
            if(id == null || id.equals("null")){
                rtv.insert();
                ResultSet rs;
                int id_travel;
                try {
                    rs = new Db().executeResultSet("select max(id) from routes_travels");
                    rs.next();
                    id_travel = rs.getInt(1);
                    rtv.setId(id_travel);
                } catch (SQLException ex) {
                    out.println(ex.getMessage());
                    return;
                }
            }
            else
            {
                rtv.setId(Integer.parseInt(id));
                new Db().executeSQL("delete from routes_times where id_travel="+id);
            }

            Object[] routes = new RouteItinerary().select("select rt from RouteItinerary rt where rt.route.id = "+ r.getId()).toArray();

            int i= type == 1 ? 0 : routes.length-1;
            int total = type == 1 ? routes.length : 0;
            for(;(i<total && total==routes.length) || (i>= total && total==0);){
                RouteItinerary rt = (RouteItinerary)routes[i];
                RouteTime time = new RouteTime();
                time.setRouteTravel(rtv);
                time.setCity(rt.getCity());
                String time_city = request.getParameter(String.valueOf(rt.getCity().getId()));
                time.setTime(Time.valueOf(time_city+":00"));
                time.insert();
                if(total==0)
                    i--;
                else
                    i++;
            }           
            response.sendRedirect("Manager/MTravels.jsp?id_route="+request.getParameter("route"));
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(RouteTimeServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(RouteTimeServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
